/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hps.view;

import hps.model.Barrier;
import hps.model.EmergencyExit;
import hps.model.Explosion;
import hps.model.Fire;
import hps.model.Pedestrian;
import hps.model.Point;
import hps.model.Room;
import hps.model.Wall;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author $Author: NIKE3500 $
 * @version $Revision: 94 $
 * @date $Date: 2013-01-22 21:08:20 +0000 (Tue, 22 Jan 2013) $
 */
public class FormMain extends javax.swing.JFrame
{

    /**
     * Speichert zuletzt gewählten Button als Tool
     */
    private JButton lastSelectedTool;
    //Filter fuer FileChooser
    private FileFilter hpsrFilter;
    private FileFilter pngFilter;
    //Letzter Punkt fuer Wand
    private Point lastClickedPoint;

    /**
     * Creates new form GUI
     */
    public FormMain()
    {
        initComponents();
        lastSelectedTool = btnPointer;

        hpsrFilter = new FileFilter()
        {
            @Override
            public boolean accept(File pathname)
            {
                return pathname.getName().toLowerCase().endsWith(".hpsr") || pathname.isDirectory();
            }

            @Override
            public String getDescription()
            {
                return "HPS-Räume(*.hpsr)";
            }
        };
        pngFilter = new FileFilter()
        {
            @Override
            public boolean accept(File pathname)
            {
                return pathname.getName().toLowerCase().endsWith(".png") || pathname.isDirectory();
            }

            @Override
            public String getDescription()
            {
                return "png-Bilder(*.png)";
            }
        };
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        java.awt.GridBagConstraints gridBagConstraints;

        splitMain = new javax.swing.JSplitPane();
        pnlToolbar = new javax.swing.JPanel();
        btnPointer = new javax.swing.JButton();
        btnRadierer = new javax.swing.JButton();
        btnWand = new javax.swing.JButton();
        btnHindernis = new javax.swing.JButton();
        btnFeuer = new javax.swing.JButton();
        btnExplosion = new javax.swing.JButton();
        btnNotaudgang = new javax.swing.JButton();
        btnMensch = new javax.swing.JButton();
        btnMenschen = new javax.swing.JButton();
        roomDrawPanel1 = new hps.view.RoomDrawPanel();
        Menu = new javax.swing.JMenuBar();
        MenuHPS = new javax.swing.JMenu();
        Beenden = new javax.swing.JMenuItem();
        MenuRaum = new javax.swing.JMenu();
        NeuerRaum = new javax.swing.JMenuItem();
        RaumOeffnen = new javax.swing.JMenuItem();
        RaumSpeichernUnter = new javax.swing.JMenuItem();
        BildSpeichern = new javax.swing.JMenuItem();
        MenuSimulation = new javax.swing.JMenu();
        Starten = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        splitMain.setDividerLocation(150);

        pnlToolbar.setLayout(new java.awt.GridLayout(9, 1));

        btnPointer.setText("Pointer");
        btnPointer.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                btnPointerMouseClicked(evt);
            }
        });
        btnPointer.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnPointer);

        btnRadierer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/radierer.png"))); // NOI18N
        btnRadierer.setText("Radierer");
        btnRadierer.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnRadierer);

        btnWand.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/wand.png"))); // NOI18N
        btnWand.setText("Wand");
        btnWand.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnWand);

        btnHindernis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/hindernis.png"))); // NOI18N
        btnHindernis.setText("Hindernis");
        btnHindernis.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnHindernis);

        btnFeuer.setForeground(java.awt.Color.red);
        btnFeuer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/feuer.png"))); // NOI18N
        btnFeuer.setText("Feuer");
        btnFeuer.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnFeuer);

        btnExplosion.setForeground(new java.awt.Color(255, 116, 0));
        btnExplosion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/explosion.png"))); // NOI18N
        btnExplosion.setText("Explosion");
        btnExplosion.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnExplosion);

        btnNotaudgang.setForeground(new java.awt.Color(12, 178, 12));
        btnNotaudgang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/notausgang.png"))); // NOI18N
        btnNotaudgang.setText("Notausgang");
        btnNotaudgang.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnNotaudgang);

        btnMensch.setForeground(new java.awt.Color(19, 19, 137));
        btnMensch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/mensch.png"))); // NOI18N
        btnMensch.setText("Mensch");
        btnMensch.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnMensch);

        btnMenschen.setForeground(new java.awt.Color(19, 19, 137));
        btnMenschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/menschen.png"))); // NOI18N
        btnMenschen.setText("Menschen");
        btnMenschen.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                toolbarButtonAction(evt);
            }
        });
        pnlToolbar.add(btnMenschen);

        splitMain.setLeftComponent(pnlToolbar);

        roomDrawPanel1.setBackground(new java.awt.Color(255, 255, 255));
        roomDrawPanel1.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                roomDrawPanel1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout roomDrawPanel1Layout = new javax.swing.GroupLayout(roomDrawPanel1);
        roomDrawPanel1.setLayout(roomDrawPanel1Layout);
        roomDrawPanel1Layout.setHorizontalGroup(
            roomDrawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 907, Short.MAX_VALUE)
        );
        roomDrawPanel1Layout.setVerticalGroup(
            roomDrawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 760, Short.MAX_VALUE)
        );

        splitMain.setRightComponent(roomDrawPanel1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(splitMain, gridBagConstraints);

        MenuHPS.setText("HPS");
        MenuHPS.setFocusCycleRoot(true);

        Beenden.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        Beenden.setText("Beenden");
        Beenden.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                BeendenActionPerformed(evt);
            }
        });
        MenuHPS.add(Beenden);

        Menu.add(MenuHPS);

        MenuRaum.setText("Raum");

        NeuerRaum.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        NeuerRaum.setText("Neuer Raum");
        NeuerRaum.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                NeuerRaumActionPerformed(evt);
            }
        });
        MenuRaum.add(NeuerRaum);

        RaumOeffnen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        RaumOeffnen.setText("Raum öffnen");
        RaumOeffnen.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                RaumOeffnenActionPerformed(evt);
            }
        });
        MenuRaum.add(RaumOeffnen);

        RaumSpeichernUnter.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        RaumSpeichernUnter.setText("Raum speichern unter");
        RaumSpeichernUnter.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                RaumSpeichernUnterActionPerformed(evt);
            }
        });
        MenuRaum.add(RaumSpeichernUnter);

        BildSpeichern.setText("Raum als Bild speichern");
        BildSpeichern.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                BildSpeichernActionPerformed(evt);
            }
        });
        MenuRaum.add(BildSpeichern);

        Menu.add(MenuRaum);

        MenuSimulation.setText("Simulation");

        Starten.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        Starten.setText("Starten");
        Starten.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                StartenActionPerformed(evt);
            }
        });
        MenuSimulation.add(Starten);

        Menu.add(MenuSimulation);

        setJMenuBar(Menu);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BeendenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BeendenActionPerformed
        System.exit(0);
    }//GEN-LAST:event_BeendenActionPerformed

    private void btnPointerMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_btnPointerMouseClicked
    {//GEN-HEADEREND:event_btnPointerMouseClicked
    }//GEN-LAST:event_btnPointerMouseClicked

    private void NeuerRaumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NeuerRaumActionPerformed
        createRoom();
    }//GEN-LAST:event_NeuerRaumActionPerformed

    private void RaumOeffnenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RaumOeffnenActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(hpsrFilter);
        if (chooser.showDialog(this, "Öffnen") == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                roomDrawPanel1.setRoom(Room.readFrom(chooser.getSelectedFile().getAbsolutePath()));
            }
            catch (IOException e)
            {
                JOptionPane.showMessageDialog(this, "Fehler beim Öffnen der Datei. Datei ist möglicherweise nicht vorhanden.");
            }
        }
    }//GEN-LAST:event_RaumOeffnenActionPerformed

    private void RaumSpeichernUnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RaumSpeichernUnterActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(hpsrFilter);
        if (chooser.showDialog(this, "Speichern") == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                roomDrawPanel1.getRoom().saveTo(chooser.getSelectedFile().getAbsolutePath());
            }
            catch (IOException e)
            {
                JOptionPane.showMessageDialog(this, "Fehler beim Öffnen der Datei. Datei ist möglicherweise bereits vorhanden und geöffnet.");
            }
        }
    }//GEN-LAST:event_RaumSpeichernUnterActionPerformed

    private void toolbarButtonAction(java.awt.event.ActionEvent evt)//GEN-FIRST:event_toolbarButtonAction
    {//GEN-HEADEREND:event_toolbarButtonAction
        if (evt.getSource() instanceof JButton)
        {
            lastSelectedTool = (JButton) evt.getSource();
            lastClickedPoint = null;
        }
    }//GEN-LAST:event_toolbarButtonAction

    private void roomDrawPanel1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_roomDrawPanel1MouseClicked
    {//GEN-HEADEREND:event_roomDrawPanel1MouseClicked
        Point p = roomDrawPanel1.getField(evt.getPoint());
        Room r = roomDrawPanel1.getRoom();
        if (!p.equals(new Point(-1, -1)))
        {
            if (lastSelectedTool == btnPointer)
            {
                //Noch keine Aktion
            }
            else if (lastSelectedTool == btnRadierer)
            {
                r.removeAt(p);
            }
            else if (lastSelectedTool == btnFeuer)
            {
                //Neues Feuer einfuegen
                r.addInfluence(new Fire(Fire.STANDARD_SPREAD_TIME, p));
            }
            else if (lastSelectedTool == btnExplosion)
            {
                r.addInfluence(new Explosion(Explosion.STANDARD_SPREAD_TIME, p, Explosion.STANDARD_RANGE));
            }
            else if (lastSelectedTool == btnWand)
            {
                if (lastClickedPoint == null)
                {
                    lastClickedPoint = p;
                }
                else
                {
                    r.addStaticInfluence(new Wall(lastClickedPoint, p));
                    lastClickedPoint = null;
                }
            }
            else if (lastSelectedTool == btnHindernis)
            {
                r.addStaticInfluence(new Barrier(p));
            }
            else if (lastSelectedTool == btnMensch)
            {
                r.addPedestrian(new Pedestrian(p));
            }
            else if (lastSelectedTool == btnMenschen)
            {
                if (lastClickedPoint == null)
                {
                    lastClickedPoint = p;
                }
                else
                {
                    randomAddPedestrians(p, lastClickedPoint);
                    lastClickedPoint = null;
                }
            }
            else if (lastSelectedTool == btnNotaudgang)
            {
                if (lastClickedPoint == null)
                {
                    lastClickedPoint = p;
                }
                else
                {
                    r.addStaticInfluence(new EmergencyExit(lastClickedPoint, p));
                    lastClickedPoint = null;
                }
            }
        }
    }//GEN-LAST:event_roomDrawPanel1MouseClicked

    private void StartenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartenActionPerformed
        FormSimulation simulation = new FormSimulation(roomDrawPanel1.getRoom().createSimulation());
        simulation.setVisible(true);
    }//GEN-LAST:event_StartenActionPerformed

    private void BildSpeichernActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_BildSpeichernActionPerformed
    {//GEN-HEADEREND:event_BildSpeichernActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(pngFilter);

        if (fc.showDialog(this, "Speichern") == JFileChooser.OPEN_DIALOG)
        {
            try
            {
                roomDrawPanel1.getRoom().saveImageTo(fc.getSelectedFile().getAbsolutePath());
            }
            catch (IOException e)
            {
                JOptionPane.showMessageDialog(this, "Fehler beim Öffnen der Datei. Datei ist möglicherweise bereits vorhanden und geöffnet.");
            }
        }
    }//GEN-LAST:event_BildSpeichernActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new FormMain().setVisible(true);
            }
        });
    }

    /**
     * Richtet das automatische Einfuegen von Pedestrians in einem Rechteck ein
     *
     * @param p1 erste Ecke
     * @param p2 zweite Ecke
     */
    private void randomAddPedestrians(Point p1, Point p2)
    {
        int count = -1;
        String input = null;
        Point l_p1 = new Point(), l_p2 = new Point();

        //Ordnen der Punkte        
        if (p1.getX() < p2.getX())
        {
            l_p1.setX(p1.getX());
            l_p2.setX(p2.getX());
        }
        else
        {
            l_p2.setX(p1.getX());
            l_p1.setX(p2.getX());

        }
        if (p1.getY() < p2.getY())
        {
            l_p1.setY(p1.getY());
            l_p2.setY(p2.getY());
        }
        else
        {
            l_p2.setY(p1.getY());
            l_p1.setY(p2.getY());
        }

        //Anzahl holen
        while (count < 0)
        {
            input = JOptionPane.showInputDialog("Bitte geben Sie die gewünschte Anzahl ein");
            if (input == null)
            {
                break;
            }
            try
            {
                count = Integer.parseInt(input);
                JOptionPane.showMessageDialog(this, String.format("Es wurden %d Fußgänger hinzugefügt!",
                        roomDrawPanel1.getRoom().addRandomPedestrians(l_p1, l_p2, count)));
            }
            catch (NumberFormatException e)
            {
                JOptionPane.showMessageDialog(this, "Keine Zahl!");
            }

        }
    }

    /**
     * Blendet Eingabemasken für neuen Raum vor und erstellt dann einen
     * entsprechenden Raum.
     */
    private void createRoom()
    {
        int x = -1, y = -1;
        String input;
        //Anzahl holen
        while (x < 0)
        {
            input = JOptionPane.showInputDialog("Bitte geben Sie die gewünschte Breite in Feldern ein\n(Feldbreite entspricht 0,4 Metern)");
            if (input == null)
            {
                return;
            }
            try
            {
                x = Integer.parseInt(input);
            }
            catch (NumberFormatException e)
            {
                JOptionPane.showMessageDialog(this, "Keine Zahl!");
            }

        }
        while (y < 0)
        {
            input = JOptionPane.showInputDialog("Bitte geben Sie die gewünschte Höhe in Feldern ein\n(Feldhöhe entspricht 0,4 Metern)");
            if (input == null)
            {
                return;
            }
            try
            {
                y = Integer.parseInt(input);
            }
            catch (NumberFormatException e)
            {
                JOptionPane.showMessageDialog(this, "Keine Zahl!");
            }
        }

        roomDrawPanel1.setRoom(new Room(x, y));
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Beenden;
    private javax.swing.JMenuItem BildSpeichern;
    private javax.swing.JMenuBar Menu;
    private javax.swing.JMenu MenuHPS;
    private javax.swing.JMenu MenuRaum;
    private javax.swing.JMenu MenuSimulation;
    private javax.swing.JMenuItem NeuerRaum;
    private javax.swing.JMenuItem RaumOeffnen;
    private javax.swing.JMenuItem RaumSpeichernUnter;
    private javax.swing.JMenuItem Starten;
    private javax.swing.JButton btnExplosion;
    private javax.swing.JButton btnFeuer;
    private javax.swing.JButton btnHindernis;
    private javax.swing.JButton btnMensch;
    private javax.swing.JButton btnMenschen;
    private javax.swing.JButton btnNotaudgang;
    private javax.swing.JButton btnPointer;
    private javax.swing.JButton btnRadierer;
    private javax.swing.JButton btnWand;
    private javax.swing.JPanel pnlToolbar;
    private hps.view.RoomDrawPanel roomDrawPanel1;
    private javax.swing.JSplitPane splitMain;
    // End of variables declaration//GEN-END:variables
}
